# Generate Makefile
import os
from deps import Dependencies
from parser import Library

ROOT_DIR = "/home/hjbai/hongjielib/src"
class Gen:
  def __init__(self, root_dir, target):
    self.__root_dir = root_dir
    self.__target = target

  def Gen(self, outputpath):
    deps_worker = Dependencies(self.__root_dir)
    deps = deps_worker.find_deps(self.__target)
    f = open(outputpath, "w")
    f.write("CC=g++\nAR=ar\nLFLAGS=-L%s/../libs\nCFLAGS=-std=c++0x -g -c -Wall -Wno-deprecated -Wno-sign-compare -I%s -I%s/build-bin -I/usr/local/include \n" % (ROOT_DIR, ROOT_DIR, ROOT_DIR));
    objs = []
    for (k, v) in deps.items():
      objs.append(v)
    # sort to make sure proto comes first.
    objs.sort(key=lambda vv: vv.libtype != Library.PROTO) 
    objfiles = []
    for v in objs:
      objfiles.append(v.write_makefile_str(f))
    if (deps[self.__target].libtype == Library.BINARY or
        deps[self.__target].libtype == Library.UNITTEST):
      Library.write_binary_str(self.__target, objfiles, f,
          deps[self.__target].libtype == Library.UNITTEST)
      f.write("all: %s\n" % (self.__target[2:].replace(":", "/")))
    else:
      Library.write_ar_str(self.__target, objfiles, f)
      f.write("all: %s\n" % (self.__target[2:].replace(":", "/")))

    f.close()

import sys    
a = Gen(ROOT_DIR, sys.argv[1])
a.Gen(sys.argv[2])
